﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ViewMaker.Core.Controls
{
    /// <summary>
    /// ItemsコントロールViewControl
    /// </summary>
    public class ItemsControlViewControl : HeaderViewControl
    {
        /// <summary>
        /// プロパティ定数
        /// </summary>
        public new class Properties : HeaderViewControl.Properties
        {
            public const string HasScrollViewer = "HasScrollViewer";
        }

        /// <summary>
        /// ScrollViewer付で表示するか
        /// </summary>
        public bool HasScrollViewer { get; set; }

        public ItemsControlViewControl()
        {
            ControlType = ViewControlType.ItemsControl;
            IsPanel = false;
            HeaderPosition = LayoutHeaderPosition.Hidden;
            ColumnSpan = 0;
        }
        /// <summary>
        /// Xamlを生成する
        /// </summary>
        /// <param name="parent"></param>
        /// <returns></returns>
        public override List<XamlNode> CreateXaml(XamlNode parent)
        {
            var list = base.CreateXaml(parent);
            XamlNode cont;
            XamlNode panel;
            if (HasScrollViewer)
            {
                cont = parent.CreateElement("ScrollViewer");
                panel = cont.AddElement("ItemsControl");
            }
            else
            {
                cont = parent.CreateElement("ItemsControl");
                panel = cont;
            }

            SetBindingAttribute(panel, "ItemsSource", Item.BindPath, true);

            if (Item.Children.Count > 0)
            {
                var temp = panel.AddElement("ItemsControl.ItemTemplate").AddElement("DataTemplate").AddElement("StackPanel");
                foreach (var child in Item.Children)
                {
                    foreach (var item in child.CreateXaml(temp))
                    {
                        temp.AppendChild(item);
                    }
                }
            }

            ApplyBaseProperty(cont);
            list.Add(cont);
            return list;
        }

        public override int? GetItemWidth(ViewControl ctrl)
        {
            if (ctrl == this) return Width;
            if (this.Item.Parent != null)
            {
                var provider = this.Item.Parent.Element as IItemPropProvider;
                if (provider != null) return provider.GetItemWidth(ctrl);
            }
            return null;
        }

        public override int? GetItemHeight(ViewControl ctrl)
        {
            if (ctrl == this) return Height;
            if (this.Item.Parent != null)
            {
                var provider = this.Item.Parent.Element as IItemPropProvider;
                if (provider != null) return provider.GetItemHeight(ctrl);
            }
            return null;
        }

    }

}
